package com.example.mall_system.service.Impl;

import com.example.mall_system.common.Result;
import com.example.mall_system.entity.Order;
import com.example.mall_system.mapper.OrderMapper;
import com.example.mall_system.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private OrderMapper orderMapper;

    // 存储支付验证码的缓存
    private final Map<String, String> paymentVerificationCodes = new ConcurrentHashMap<>();
    
    // 存储支付状态的缓存
    private final Map<String, PaymentStatus> paymentStatusMap = new ConcurrentHashMap<>();

    @Override
    @Transactional
    public Result<Object> processPayment(Long orderId, Integer paymentMethod) {
        // 获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }

        // 检查订单状态
        if (order.getStatus() != 0) {
            return Result.error(400, "订单状态错误，只能支付待支付订单");
        }

        // 生成支付验证码
        String verificationCode = generateVerificationCode();
        String paymentKey = orderId + "_" + paymentMethod;
        paymentVerificationCodes.put(paymentKey, verificationCode);
        
        // 设置支付状态为等待验证
        paymentStatusMap.put(paymentKey, PaymentStatus.WAITING_VERIFICATION);

        // 模拟支付处理延迟
        try {
            Thread.sleep(1000 + new Random().nextInt(2000)); // 1-3秒随机延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 根据支付方式模拟不同的处理逻辑
        String paymentResult = simulatePaymentByMethod(paymentMethod, order.getTotalPrice());
        
        if ("SUCCESS".equals(paymentResult)) {
            // 更新订单状态
            order.setStatus(1); // 已支付
            order.setPaymentMethod(paymentMethod);
            order.setPaymentTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            order.setUpdateTime(new java.util.Date());
            
            int updateResult = orderMapper.updateStatus(order);
            if (updateResult > 0) {
                // 清除支付缓存
                paymentVerificationCodes.remove(paymentKey);
                paymentStatusMap.remove(paymentKey);
                
                Map<String, Object> paymentInfo = new HashMap<>();
                paymentInfo.put("orderId", orderId);
                paymentInfo.put("paymentMethod", getPaymentMethodName(paymentMethod));
                paymentInfo.put("paymentTime", order.getPaymentTime());
                paymentInfo.put("verificationCode", verificationCode);
                
                return Result.success(paymentInfo);
            } else {
                return Result.error(500, "支付处理失败");
            }
        } else {
            paymentStatusMap.put(paymentKey, PaymentStatus.FAILED);
            return Result.error(500, "支付失败：" + paymentResult);
        }
    }

    @Override
    public Result<Boolean> verifyPayment(Long orderId, String paymentData) {
        // 获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }

        // 检查订单是否已支付
        if (order.getStatus() == 1) {
            return Result.success(true);
        } else {
            return Result.success(false);
        }
    }

    @Override
    @Transactional
    public Result<Object> refundPayment(Long orderId, String reason) {
        // 获取订单信息
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            return Result.error(404, "订单不存在");
        }

        // 检查订单状态
        if (order.getStatus() != 1) {
            return Result.error(400, "只能退款已支付的订单");
        }

        // 模拟退款处理
        try {
            Thread.sleep(1000 + new Random().nextInt(2000)); // 1-3秒随机延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 模拟退款成功率 (98%成功率)
        if (new Random().nextInt(100) < 2) {
            return Result.error(500, "退款失败，请重试");
        }

        // 更新订单状态为已取消
        order.setStatus(4); // 已取消
        order.setCancellationTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        order.setUpdateTime(new java.util.Date());
        
        int updateResult = orderMapper.updateStatus(order);
        if (updateResult > 0) {
            Map<String, Object> refundInfo = new HashMap<>();
            refundInfo.put("orderId", orderId);
            refundInfo.put("refundTime", order.getCancellationTime());
            refundInfo.put("reason", reason);
            
            return Result.success(refundInfo);
        } else {
            return Result.error(500, "退款处理失败");
        }
    }

    // 验证支付验证码
    public Result<String> verifyPaymentCode(Long orderId, Integer paymentMethod, String verificationCode) {
        String paymentKey = orderId + "_" + paymentMethod;
        String storedCode = paymentVerificationCodes.get(paymentKey);
        
        if (storedCode == null) {
            return Result.error(400, "支付验证码已过期或不存在");
        }
        
        if (!storedCode.equals(verificationCode)) {
            return Result.error(400, "支付验证码错误");
        }
        
        // 验证成功，清除验证码
        paymentVerificationCodes.remove(paymentKey);
        paymentStatusMap.put(paymentKey, PaymentStatus.VERIFIED);
        
        return Result.success("验证码验证成功");
    }

    // 获取支付状态
    public Result<PaymentStatus> getPaymentStatus(Long orderId, Integer paymentMethod) {
        String paymentKey = orderId + "_" + paymentMethod;
        PaymentStatus status = paymentStatusMap.get(paymentKey);
        return Result.success(status != null ? status : PaymentStatus.UNKNOWN);
    }

    // 取消支付
    public Result<String> cancelPayment(Long orderId, Integer paymentMethod) {
        String paymentKey = orderId + "_" + paymentMethod;
        paymentVerificationCodes.remove(paymentKey);
        paymentStatusMap.remove(paymentKey);
        return Result.success("支付已取消");
    }

    private String generateVerificationCode() {
        // 生成6位数字验证码
        return String.format("%06d", new Random().nextInt(1000000));
    }

    private String simulatePaymentByMethod(Integer paymentMethod, java.math.BigDecimal amount) {
        Random random = new Random();
        
        switch (paymentMethod) {
            case 0: // 支付宝
                // 支付宝成功率较高
                return random.nextInt(100) < 95 ? "SUCCESS" : "BALANCE_INSUFFICIENT";
            case 1: // 微信支付
                // 微信支付成功率较高
                return random.nextInt(100) < 94 ? "SUCCESS" : "NETWORK_ERROR";
            case 2: // 银行卡支付
                // 银行卡支付成功率稍低
                return random.nextInt(100) < 92 ? "SUCCESS" : "CARD_DECLINED";
            default:
                return "UNSUPPORTED_PAYMENT_METHOD";
        }
    }

    private String getPaymentMethodName(Integer paymentMethod) {
        switch (paymentMethod) {
            case 0: return "支付宝";
            case 1: return "微信支付";
            case 2: return "银行卡支付";
            default: return "未知支付方式";
        }
    }

    // 支付状态枚举
    public enum PaymentStatus {
        WAITING_VERIFICATION, // 等待验证
        VERIFIED,             // 已验证
        SUCCESS,              // 支付成功
        FAILED,               // 支付失败
        CANCELLED,            // 已取消
        UNKNOWN               // 未知状态
    }
} 